package com.afd.ozblip.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.afd.ozblip.entity.CategoryEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.StringUtil;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

public class AddBusinessActivity extends BaseActivity {

	/****************** 视图变量 **************************/
	private EditText businessNameEt;
	private Spinner parentClassSp;
	private Spinner childClassSp;
	private Spinner citySp;
	private Spinner districtSp;
	private EditText businessAddressEt;
	private EditText businessNearbyEt;
	private EditText businessTelEt;

	// private Spinner time1Sp;
	// private Spinner time2Sp;
	// private Spinner time3Sp;
	// private Spinner time4Sp;
	private LinearLayout timeLayout;
	private TimePicker beginTimeTp;
	private TimePicker endTimeTp;
	private TextView beginTimeTv;
	private TextView endTimeTv;
	private Button submitBtn;

	/****************** 数据变量 **************************/
	private static final String[] week = { "星期一", "星期二", "星期三", "星期四", "星期五",
			"星期六", "星期天" };
	private static final String[] hour = { "01", "02", "03", "04", "05", "06",
			"07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17",
			"18", "19", "20", "21", "22", "23", "24" };
	private static final String[] minute = { "01", "02", "03", "04", "05",
			"06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16",
			"17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27",
			"28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38",
			"39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49",
			"50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60" };
	private List<HashMap<String, Object>> cityList = null;
	private List<HashMap<String, Object>> nowAreaList;
	private List<CategoryEntity> categoryList;
	private String businessNameStr;
	private String businessAddressStr;
	private String businessNearbyStr;
	private String businessTelStr;
	private Map<String, Object> resultMap;
	private String beginTimeStr="8:00";
	private String endTimeStr="22:00";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_business);
		// 启动返回功能
		toBack();
		// 寻找视图
		findViews();
		// 设置监听
		setListeners();
		// 获取参数
		getBundle();
		// 获取城市列表
		requestAllCityData();
		// 初始化下拉框
		initData();
	}

	/**
	 * 寻找视图
	 */
	public void findViews() {
		this.businessNameEt = (EditText) findViewById(R.id.et_add_business_name);
		this.parentClassSp = (Spinner) findViewById(R.id.sp_add_business_pClass);
		this.childClassSp = (Spinner) findViewById(R.id.sp_add_business_cClass);
		this.citySp = (Spinner) findViewById(R.id.sp_add_business_city);
		this.districtSp = (Spinner) findViewById(R.id.sp_add_business_district);
		this.businessAddressEt = (EditText) findViewById(R.id.et_add_business_address);
		this.businessNearbyEt = (EditText) findViewById(R.id.et_add_business_nearby);
		this.businessTelEt = (EditText) findViewById(R.id.et_add_business_tel);
		this.timeLayout = (LinearLayout) findViewById(R.id.ll_notice_time);
		this.beginTimeTv = (TextView) findViewById(R.id.tv_notice_beginTime);
		this.endTimeTv = (TextView) findViewById(R.id.tv_notice_endTime);
		// this.time1Sp = (Spinner) findViewById(R.id.sp_add_business_time1);
		// this.time2Sp = (Spinner) findViewById(R.id.sp_add_business_time2);
		// this.time3Sp = (Spinner) findViewById(R.id.sp_add_business_time3);
		// this.time4Sp = (Spinner) findViewById(R.id.sp_add_business_time4);
		this.submitBtn = (Button) findViewById(R.id.btn_add_business_submit);
	}

	/**
	 * 设置监听
	 */
	public void setListeners() {
		View.OnClickListener moreClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.btn_add_business_submit:
					businessNameStr = businessNameEt.getText().toString()
							.trim();
					businessAddressStr = businessAddressEt.getText().toString()
							.trim();
					businessNearbyStr = businessNearbyEt.getText().toString()
							.trim();
					businessTelStr = businessTelEt.getText().toString().trim();
					if (verifyData()) {
						requestAddBusinessData();
					}
					break;
				case R.id.ll_notice_time:
					final Dialog dlg = new Dialog(AddBusinessActivity.this,
							R.style.listDialog);
					dlg.show();
					Window window = dlg.getWindow();
					// *** 主要就是在这里实现这种效果的.
					// 设置窗口的内容页面,notice_time.xml文件中定义view内容
					window.setContentView(R.layout.notice_time);
					// 初始视图
					beginTimeTp = (TimePicker) window
							.findViewById(R.id.tp_notice_beginTime);
					endTimeTp = (TimePicker) window
							.findViewById(R.id.tp_notice_endTime);
					String[] btArr = beginTimeStr.split(":");
					beginTimeTp.setCurrentHour(Integer.parseInt(btArr[0]));
					beginTimeTp.setCurrentMinute(Integer.parseInt(btArr[1]));
					String[] etArr = endTimeStr.split(":");
					endTimeTp.setCurrentHour(Integer.parseInt(etArr[0]));
					endTimeTp.setCurrentMinute(Integer.parseInt(etArr[1]));
					// 为确认按钮添加事件,执行退出应用操作
					Button ok = (Button) window
							.findViewById(R.id.btn_notice_ok);
					ok.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							String bTmin = beginTimeTp.getCurrentMinute() < 10 ? "0"
									+ beginTimeTp.getCurrentMinute()
									: beginTimeTp.getCurrentMinute() + "";
							beginTimeTv.setText(beginTimeTp.getCurrentHour()
									+ ":" + bTmin);
							String eTmin = endTimeTp.getCurrentMinute() < 10 ? "0"
									+ endTimeTp.getCurrentMinute()
									: endTimeTp.getCurrentMinute() + "";
							endTimeTv.setText(endTimeTp.getCurrentHour() + ":"
									+ eTmin);
							beginTimeStr = beginTimeTv.getText().toString();
							endTimeStr = endTimeTv.getText().toString();
							dlg.cancel();
						}
					});
					// 关闭alert对话框架
					Button cancel = (Button) window
							.findViewById(R.id.btn_notice_cancel);
					cancel.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							dlg.cancel();
						}
					});
					break;
				default:
					break;
				}
			}
		};
		this.submitBtn.setOnClickListener(moreClick);
		this.timeLayout.setOnClickListener(moreClick);
	}

	/**
	 * 获取传递的参数
	 */
	private void getBundle() {
		// Intent intent = getIntent();
	}

	private boolean verifyData() {
		if (StringUtil.isNullOrEmpty(businessNameStr)) {
			showShortToast("请输入商家名称");
			return false;
		}
		if (citySp.getSelectedItem() == null) {
			showShortToast("请选择城市");
			return false;
		}
		if (districtSp.getSelectedItem() == null) {
			showShortToast("请选择区域");
			return false;
		}
		if (StringUtil.isNullOrEmpty(businessAddressStr)) {
			showShortToast("请输入商家地址");
			return false;
		}
		if (StringUtil.isNullOrEmpty(businessNearbyStr)) {
			showShortToast("请输入商家靠近地点");
			return false;
		}
		if (StringUtil.isNullOrEmpty(businessTelStr)) {
			showShortToast("请输入商家电话");
			return false;
		}
		return true;
	}

	private void initData() {
		categoryList = Constants.getCategoryList();
		int classLen = categoryList.size();
		String[] m = new String[classLen];
		for (int i = 0; i < classLen-1; i++) {
			m[i] = categoryList.get(i+1).getParentClassName();
		}
		// 将可选内容与SimpleAdapter连接起来
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, m);

		// 设置下拉列表的风格
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// 将adapter 添加到spinner中
		parentClassSp.setAdapter(adapter);

		// 添加事件Spinner事件监听
		parentClassSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View v,
					int position, long arg3) {
				TextView tv = (TextView) v;
				tv.setTextColor(getResources().getColor(R.color.black));
				tv.setGravity(Gravity.LEFT);
				// 清空上一次存储的子集
				setChildClassData(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		// // 设置时间1
		// // 将可选内容与ArrayAdapter连接起来
		// ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(this,
		// android.R.layout.simple_spinner_item, hour);
		// // 设置下拉列表的风格
		// hourAdapter
		// .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// // 将可选内容与ArrayAdapter连接起来
		// ArrayAdapter<String> minuteAdapter = new ArrayAdapter<String>(this,
		// android.R.layout.simple_spinner_item, minute);
		// // 设置下拉列表的风格
		// minuteAdapter
		// .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// // 将adapter 添加到spinner中
		// time1Sp.setAdapter(hourAdapter);
		//
		// // 添加事件Spinner事件监听
		// time1Sp.setOnItemSelectedListener(new OnItemSelectedListener() {
		//
		// @Override
		// public void onItemSelected(AdapterView<?> arg0, View v,
		// int position, long arg3) {
		// TextView tv = (TextView) v;
		// tv.setTextColor(getResources().getColor(R.color.black));
		// tv.setGravity(Gravity.LEFT);
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		//
		// }
		// });
		// // 将adapter 添加到spinner中
		// time2Sp.setAdapter(minuteAdapter);
		//
		// // 添加事件Spinner事件监听
		// time2Sp.setOnItemSelectedListener(new OnItemSelectedListener() {
		//
		// @Override
		// public void onItemSelected(AdapterView<?> arg0, View v,
		// int position, long arg3) {
		// TextView tv = (TextView) v;
		// tv.setTextColor(getResources().getColor(R.color.black));
		// tv.setGravity(Gravity.LEFT);
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		//
		// }
		// });
		// // 将adapter 添加到spinner中
		// time3Sp.setAdapter(hourAdapter);
		//
		// // 添加事件Spinner事件监听
		// time3Sp.setOnItemSelectedListener(new OnItemSelectedListener() {
		//
		// @Override
		// public void onItemSelected(AdapterView<?> arg0, View v,
		// int position, long arg3) {
		// TextView tv = (TextView) v;
		// tv.setTextColor(getResources().getColor(R.color.black));
		// tv.setGravity(Gravity.LEFT);
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		//
		// }
		// });
		// // 将adapter 添加到spinner中
		// time4Sp.setAdapter(minuteAdapter);
		//
		// // 添加事件Spinner事件监听
		// time4Sp.setOnItemSelectedListener(new OnItemSelectedListener() {
		//
		// @Override
		// public void onItemSelected(AdapterView<?> arg0, View v,
		// int position, long arg3) {
		// TextView tv = (TextView) v;
		// tv.setTextColor(getResources().getColor(R.color.black));
		// tv.setGravity(Gravity.LEFT);
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		//
		// }
		// });
	}

	private void setChildClassData(int pIndex) {
		List<String> childList = categoryList.get(pIndex).getChildClassList();
		int classLen = childList.size();
		String[] m = new String[classLen];
		for (int i = 0; i < classLen; i++) {
			m[i] = childList.get(i);
		}
		// 将可选内容与SimpleAdapter连接起来
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, m);

		// 设置下拉列表的风格
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// 将adapter 添加到spinner中
		childClassSp.setAdapter(adapter);

		// 添加事件Spinner事件监听
		childClassSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View v,
					int position, long arg3) {
				TextView tv = (TextView) v;
				tv.setTextColor(getResources().getColor(R.color.black));
				tv.setGravity(Gravity.LEFT);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
	}

	// TODO 获取添加商家数据
	/**
	 * 获取添加商家数据
	 */
	private void requestAddBusinessData() {
		AsyncLoadData ald = new AsyncLoadData(this, "添加中...",
				new AsyncAction() {

					@Override
					public void doLoad() throws Exception {
						// 获取提交参数
						Map<String, Object> addDishParamMap = new HashMap<String, Object>();
						addDishParamMap.put("userId",
								commonUserInfo.getUserId());
						addDishParamMap.put("sellerName", businessNameStr);
						addDishParamMap.put("parClass", parentClassSp
								.getSelectedItem().toString());
						addDishParamMap.put("chiClass", childClassSp
								.getSelectedItem().toString());
						addDishParamMap.put("city",
								cityList.get(citySp.getSelectedItemPosition())
										.get("cityId"));
						addDishParamMap.put(
								"area",
								nowAreaList.get(
										districtSp.getSelectedItemPosition())
										.get("areaId"));
						addDishParamMap.put("address", businessAddressStr);
						addDishParamMap.put("near", businessNearbyStr);
						addDishParamMap.put("telPhone", businessTelStr);
						addDishParamMap.put("workTimeForm", beginTimeStr);
						addDishParamMap.put("workTimeTo", endTimeStr);
						// addDishParamMap.put("workTimeForm", time1Sp
						// .getSelectedItem().toString()
						// + ":"
						// + time2Sp.getSelectedItem().toString());
						// addDishParamMap.put("workTimeTo", time3Sp
						// .getSelectedItem().toString()
						// + ":"
						// + time4Sp.getSelectedItem().toString());
						// 发送请求
						byte[] bAddBusiness = HttpUtil.requestByPost(
								AddBusinessActivity.this,
								Constants.ADD_SELLER_API, addDishParamMap);
						if (bAddBusiness != null) {
							resultMap = new ParseJson()
									.parseAddResultJson(bAddBusiness);
						}
					}

					@Override
					public void loadEnd() throws Exception {
						boolean returnFlg = (Boolean) resultMap
								.get("returnFlg");
						if (returnFlg) {
							showShortToast(AddBusinessActivity.this, resultMap
									.get("regMessage").toString(), true);
							finish();
						} else {
							System.out.println(resultMap.get("regMessage")
									.toString());
							showShortToast(AddBusinessActivity.this, "添加失败",
									true);
						}
					}

				});
		ald.execute(0);

	}

	// TODO 获取添加商家数据
	/**
	 * 获取城市列表数据
	 */
	private void requestAllCityData() {
		AsyncLoadData ald = new AsyncLoadData(this, "", new AsyncAction() {

			@Override
			public void doLoad() throws Exception {
				// 获取提交参数
				Map<String, Object> addDishParamMap = new HashMap<String, Object>();
				// 发送请求
				byte[] bCity = HttpUtil.requestByPost(AddBusinessActivity.this,
						Constants.CITY_LIST_API, addDishParamMap);
				if (bCity != null) {
					cityList = new ParseJson().parseCityListJson(bCity);
				}
			}

			@Override
			public void loadEnd() throws Exception {

				// 将可选内容与SimpleAdapter连接起来
				SimpleAdapter adapter = new SimpleAdapter(
						AddBusinessActivity.this, cityList,
						android.R.layout.simple_spinner_item,
						new String[] { "cityName" },
						new int[] { android.R.id.text1 });

				// 设置下拉列表的风格
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

				// 将adapter 添加到spinner中
				citySp.setAdapter(adapter);

				// 添加事件Spinner事件监听
				citySp.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View v,
							int position, long arg3) {
						TextView tv = (TextView) v;
						tv.setTextColor(getResources().getColor(R.color.black));
						tv.setGravity(Gravity.LEFT);
						String cityName = cityList.get(position)
								.get("cityName").toString();
						requestAreaListData(cityName);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}
				});
			}

		});
		ald.execute(0);

	}

	/**
	 * 获取商区列表数据
	 */
	private void requestAreaListData(final String cityName) {

		AsyncLoadData ald = new AsyncLoadData(this, "", new AsyncAction() {

			@Override
			public void doLoad() throws Exception {
				// 获取提交参数
				Map<String, Object> addReviewParamMap = new HashMap<String, Object>();
				addReviewParamMap.put("cityName", cityName);
				// 发送请求
				byte[] bAreaList = HttpUtil.requestByPost(
						AddBusinessActivity.this, Constants.AREA_LIST_API,
						addReviewParamMap);
				if (bAreaList != null) {
					nowAreaList = new ParseJson().parseAreaListJson(bAreaList);
				}

			}

			@Override
			public void loadEnd() throws Exception {
				// 将可选内容与ArrayAdapter连接起来
				SimpleAdapter adapter = new SimpleAdapter(
						AddBusinessActivity.this, nowAreaList,
						android.R.layout.simple_spinner_item,
						new String[] { "areaName" },
						new int[] { android.R.id.text1 });

				// 设置下拉列表的风格
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

				// 将adapter 添加到spinner中
				districtSp.setAdapter(adapter);

				// 添加事件Spinner事件监听
				districtSp
						.setOnItemSelectedListener(new OnItemSelectedListener() {

							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View v, int position, long arg3) {
								TextView tv = (TextView) v;
								tv.setTextColor(getResources().getColor(
										R.color.black));
								tv.setGravity(Gravity.LEFT);
								String cityName = nowAreaList.get(position)
										.get("areaName").toString();
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {

							}
						});
			}

		});
		ald.execute(0);
	}
}